package com.googlecode.jmicroerp.wicket.components;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.wicket.request.resource.AbstractResource;
import org.apache.wicket.request.resource.caching.FilenameWithVersionResourceCachingStrategy;
import org.apache.wicket.request.resource.caching.IResourceCachingStrategy;
import org.apache.wicket.request.resource.caching.IStaticCacheableResource;
import org.apache.wicket.request.resource.caching.version.IResourceVersion;

/**
 *
 * @author Alexandru.Codescu
 */
public class FileResource extends AbstractResource {
    private String uploadPath;
    private String resourceName;
    private static final int MAX_BUFFER_SIZE = 1024;

    public FileResource(String uploadPath, String resourceName) {
        this.uploadPath = uploadPath;
        this.resourceName = resourceName;
    }

    @Override
    protected IResourceCachingStrategy getCachingStrategy() {
        return new FilenameWithVersionResourceCachingStrategy(resourceName, new IResourceVersion() {

            @Override
            public String getVersion(IStaticCacheableResource iscr) {
                return "1";
            }
        });
    }
    
    @Override
    protected ResourceResponse newResourceResponse(Attributes atrbts) {
        try {
            final InputStream input = new FileInputStream(uploadPath + "/" + resourceName);

            ResourceResponse resourceResponse = new ResourceResponse();
            resourceResponse.setWriteCallback(new WriteCallback() {
                @Override
                public void writeData(Attributes atrbts) throws IOException {
                    byte[] buffer = new byte[MAX_BUFFER_SIZE];
                    int size = -1;
                    while ((size = input.read(buffer)) != -1) {
                        atrbts.getResponse().write(buffer, 0, size);
                    }
                    input.close();
                }
            });
            return resourceResponse;
        } catch (IOException ioex) {
        }
        return new ResourceResponse();
    }
}
